package com.peak.spring.boot.api.entity;

import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;

import com.peak.spring.boot.api.constant.Constants;
import com.peak.spring.boot.tools.Converts;
import com.peak.spring.boot.tools.Emptys;

import lombok.Getter;
import lombok.Setter;

@MappedSuperclass
@Getter
@Setter
public abstract class TreeEntity<T> extends DefaultStategyEntity implements Comparable<TreeEntity<T>> {

	private static final long serialVersionUID = Constants.SERIAL_VERSION;

	/** 排序 */
	@NotNull
	protected String lineNo;

	/** 等级 */
	@NotNull
	protected Integer Level;

	/** 序号 */
	@NotNull
	protected Integer sortNo;

	/** 父节点 */
	protected T parent;

	@Transient
	public abstract T getParent();

	public void setParent(T parent) {
		this.parent = parent;
	}

	@Override
	public int compareTo(TreeEntity<T> o) {
		String l1 = this.lineNo;
		String l2 = o.lineNo;
		if (Emptys.isEmpty(l1)) {
			return 1;
		}
		if (Emptys.isEmpty(l2)) {
			return -1;
		}
		String[] l1s = StringUtils.split(l1, "."); 
		String[] l2s = StringUtils.split(l2, ".");
		int result = l1s.length - l2s.length;
		if (result == 0) {
			for (int i = 0; i < l1s.length; i++) {
				result = Converts.toInt(l1s[i]) - Converts.toInt(l2s[i]);
				if (result != 0) {
					return result;
				}
			}
		}
		return result;
	}
}
